var express = require("express");
var db = require("../libs/index.js");
var router = express.Router();
var Mqtt = require('../models/mqtt.model')(db.sequelize, db.Sequelize);

// 查看所有传感器
router.get("/", async function (req, res) {
  let skip = 0,
    limit = 100;
  if (req.query && req.query.skip && req.query.limit) {
    skip = req.query.skip;
    limit = req.query.limit;
  }

  const data = await Mqtt.findAll()

  res.json({
    success: true,
    data: data,
  });
});

// 根据id查询
router.get("/:id", async (req, res) => {
  // console.log(req.query)
  const limit = +req.query.limit || 100;
  const model = await Mqtt.findByPk(req.params.id);
  res.json(model);
});

// 根据device_id查询
// http://localhost:8027/mqtt?device_id=%22esp_device001_370098%22
router.get("/", async (req, res) => {
  const device_id = req.query.device_id;
  var condition = device_id ? { device_id: { [Op.like]: `%${device_id}%` } } : null;
  const model = await Mqtt.findAll({ where: condition });
  res.json(model);
});

// 根据id修改资源
router.put("/:id", async (req, res) => {
     const id = req.params.id;
  const model = await Mqtt.update (req.body,{ where:{ id:id} });
  res.json(model);
});

module.exports = router;